﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Royalsoft.Common;
using System.IO;
using System.Text;

namespace NJL.Web
{
    public partial class RegisterActive : BasePageVisitor
    {
        private readonly BLL.NJL_USER bll = new BLL.NJL_USER();
        NJL.BLL.NJL_PERSON bllPerson = new BLL.NJL_PERSON();
        NJL.Model.NJL_PERSON modelPerson = new Model.NJL_PERSON();
        NJL.Model.NJL_USER modelUser = new Model.NJL_USER();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (UserId != "")
                {
                    modelUser = bll.GetModel(UserId);                         
                    txtEmail.Text = modelUser.EMAIL;
                }

            }
            if (Request.QueryString["option"] == "active")
            {
                string strEmail = Request.QueryString["email"];
                string strQQ = Request.QueryString["qq"];
                string strCode = Request.QueryString["code"];
                string strType = Request.QueryString["type"];
                UserActive(strEmail, strQQ, strCode, strType);
                divRegisterActive.Style["display"] = "none";
                divRegisterOK.Style["display"] = "black";
            }
            else
            {
                divRegisterActive.Style["display"] = "none";
                divRegisterOK.Style["display"] = "black";
            }
            LoadPageSEO();
        }



        /// <summary>
        /// 加载页面SEO
        /// </summary>
        private void LoadPageSEO()
        {
            Page.Title = "账户激活-" + WEBSITE_SYS_BASE.WEBSITE_NAME;

            //HtmlMeta myMeta = new HtmlMeta();
            //myMeta.Name = "Keywords";
            //myMeta.Content = WEBSITE_SYS_BASE.WEBSITE_KEYWORDS;
            //this.Header.Controls.Add(myMeta);

            //HtmlMeta myMeta1 = new HtmlMeta();
            //myMeta1.Name = "Description";
            //myMeta1.Content = WEBSITE_SYS_BASE.WEBSITE_DESCRIPTION;
            //this.Header.Controls.Add(myMeta1);
        }

        private void UserActive(string Email, string QQ, string Code, string LoginType)
        {

            if (LoginType.ToLower() == "qq")
            {
                Model.NJL_USER model = bll.GetModelByQQ(QQ);
                if (model == null)
                {
                    //非法操作，转向首页
                    MessageBox.ShowAndRedirect(this, "激活链接有误,请检查后再试！或联系网络管理员！或重新登录，再次获取激活邮件", "/");
                    return;
                }
                if (model.TYPE_CODE == "0")
                {
                    //用户已激活，请登录,转向登录页面
                    MessageBox.ShowAndRedirect(this, "此账户已激活，请登录", "Login.aspx");
                    return;
                }
                if (model.TYPE_CODE == "4")
                {
                    //用户已禁用，请登录,转向首页
                    MessageBox.ShowAndRedirect(this, "此账户已被禁用", "/");
                    return;
                }
                if (model.AUTHENTICATION_CODE_QQ == Code)
                {
                    model.QQ_ACTIVE = 1;
                    model.TYPE_CODE = "0";
                    bll.Update(model);//更新用户状态为激活
                    //---
                    Session.Add("userid", model.ID);
                    Session.Add("username", model.USER_NAME);
                    Session.Add("usertype", model.TYPE_CODE);
                    //--
                    Royalsoft.Common.MessageBox.ShowAndRedirect(this, "账户激活成功！", "RegisterTow.aspx");
                }
                else
                {
                    //非法操作，转向首页
                    MessageBox.ShowAndRedirect(this, "非法操作！", "/");
                    return;
                }
            }
            else if (LoginType.ToLower() == "email")
            {
                Model.NJL_USER model = bll.GetModelByEmail(Email);
                if (model == null)
                {
                    //非法操作，转向首页
                    MessageBox.ShowAndRedirect(this, "激活链接有误,请检查后再试！或联系网络管理员！或重新登录，再次获取激活邮件！", "/");
                    return;
                }

                if (model.TYPE_CODE == "2")
                {
                    //用户已激活，请登录,转向登录页面
                    MessageBox.ShowAndRedirect(this, "此账户已激活，请登录", "Login.aspx");
                    return;
                }

                if (model.TYPE_CODE == "4")
                {
                    //用户已禁用，请登录,转向首页
                    MessageBox.ShowAndRedirect(this, "此账户已被禁用", "/");
                    return;
                }

                if (model.AUTHENTICATION_CODE_EMAIL == Code)
                {
                    model.EMAIL_ACTIVE = 1;
                    model.TYPE_CODE = "2";
                    bll.Update(model);                        //更新用户状态为激活
                    //---
                    Session.Add("userid", model.ID);
                    Session.Add("username", model.USER_NAME);
                    Session.Add("usertype", model.TYPE_CODE);
                    //--
                    modelPerson.ID = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100, 999).ToString();
                    modelPerson.NJL_SYS_BASE_ID = WEBSITE_CODE;
                    modelPerson.CREATE_DATE_TIME = DateTime.Now;
                    modelPerson.NJL_USER_ID = UserId;
                    if (bllPerson.Add(modelPerson))
                    {
                        MessageBox.ShowAndRedirect(this, "账户激活成功", "/AdminVisitor/Default.aspx");
                    }
                }
                else
                {
                    //非法操作，转向首页
                    MessageBox.ShowAndRedirect(this, "非法操作！", "/");
                    return;
                }
            }

        }

        private System.Net.Mail.MailMessage RegisterMail(string txtMailTo, string Email, string QQ, string Code, string Type, string LoginPassword, string RegisterDateTime)
        {
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();

            System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["MailAddressFrom"], txtMailTo.Trim());
            mm.Subject = System.Configuration.ConfigurationManager.AppSettings["WebSiteName"] + "-账户验证激活邮件";
            mm.Body = GetEmailBody(txtMailTo, Email, QQ, Code, Type, LoginPassword, RegisterDateTime);
            mm.IsBodyHtml = true;
            mm.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");
            smtp.Send(mm);
            return mm;
        }

        private static string GetEmailBody(string txtMailTo, string Email, string QQ, string Code, string Type, string LoginPassword, string RegisterDateTime)
        {
            string strRegisterOkUrl = "http://" + System.Configuration.ConfigurationManager.AppSettings["WebSiteDomain"] + "/RegisterActive.aspx?option=active&type=" + Type + "&email=" + Email + "&qq=" + QQ + "&code=" + Code;
            string strWebsiteDomain = "http://" + System.Configuration.ConfigurationManager.AppSettings["WebSiteDomain"];
            string strWebsiteName = System.Configuration.ConfigurationManager.AppSettings["WebSiteName"];
            string strWebsiteCode = System.Configuration.ConfigurationManager.AppSettings["WebSiteCode"];
            string strRegisterUserName = txtMailTo;
            string strRegisterPassword = LoginPassword;
            string strRegisterDateTime = RegisterDateTime;


            Encoding code = Encoding.GetEncoding("GB2312");
            // 读取模板文件 
            string temp = HttpContext.Current.Server.MapPath("~/EmailTemplate/RegisterOK.html");
            StreamReader sr = null;
            //StreamWriter sw = null;
            string str = "";
            try
            {
                sr = new StreamReader(temp, code);
                str = sr.ReadToEnd(); // 读取文件 
            }
            catch (Exception exp)
            {
                HttpContext.Current.Response.Write(exp.Message);
                HttpContext.Current.Response.End();
                sr.Close();
            }

            // 替换内容 
            // 这时,模板文件已经读入到名称为str的变量中了 
            str = str.Replace("{$WebSiteDomain$}", strWebsiteDomain); //模板页中的ShowArticle 
            str = str.Replace("{$WebSiteCode$}", strWebsiteCode);
            str = str.Replace("{$WebSiteName$}", strWebsiteName);
            str = str.Replace("{$RegisterOkUserName$}", strRegisterUserName);
            str = str.Replace("{$RegisterOkPassword$}", strRegisterPassword);
            str = str.Replace("{$RegisterActiveUrl$}", strRegisterOkUrl);
            str = str.Replace("{$RegisterOkDateTime$}", strRegisterDateTime);

            return str;
        }
        protected void btnSubmitEmail_Click(object sender, EventArgs e)
        {
            //
            if (Session["CheckCode"] != null)
            {
                if (Session["CheckCode"].ToString().ToLower() != txtVCode.Text.ToLower())
                {
                    MessageBox.Show(this, "验证码输入有误！");
                    Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>$('#divReSendEmail').show();</script>");
                    return;
                }

                Model.NJL_USER model = bll.GetModelByEmail(txtEmail.Text.Trim());
                if (model == null)
                {
                    //非法操作，转向首页
                    //MessageBox.ShowAndRedirect(this, "此邮箱不存在，请确认邮箱是否输入有误", "/");
                    Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('该邮箱账号与当前注册时的账号不一致，请查证后重新输入');$('#divReSendEmail').show();</script>");
                    return;
                }
                if (model.TYPE_CODE == "-1"||model.EMAIL!=txtEmail.Text.Trim())
                {
                    //用户已激活，请登录,转向登录页面
                    RegisterMail(model.EMAIL, model.EMAIL, "", model.AUTHENTICATION_CODE_EMAIL, "email", model.USER_PASSWORD, model.CREATE_DATE_TIME.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                    MessageBox.ShowAndRedirect(this, "激活邮件发送成功，请查收", "/");
                    return;
                }
                if (model.TYPE_CODE == "0")
                {
                    //用户已激活，请登录,转向登录页面
                    MessageBox.ShowAndRedirect(this, "此邮箱已激活，请登录", "Login.aspx");
                    return;
                }

                if (model.TYPE_CODE == "4")
                {
                    //用户已禁用，请登录,转向首页
                    MessageBox.ShowAndRedirect(this, "此邮箱已被禁用", "/");
                    return;
                }
            }
            else
            {
                Response.Redirect(Request.RawUrl);
            }
        }
    }
}